package com.example.springboot.analyze;


import jeasy.analysis.MMAnalyzer;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

import java.io.IOException;

/**
 * Created by tangmayao on 2018/4/4.
 */
public class ChineseAnalyze {

    String[] chineseFragments = new String[]{
            "CSDN.NET - 全球最大中文IT社区，为IT专业技术人员提供最全面的信息传播和服务平台",
            "京华时报1月23日报道 昨天，受一股来自中西伯利亚的强冷空气影响，本市出现大风降温天气，白天最高气温只有零下7摄氏度，同时伴有6到7级的偏北风。"
    };

    public void analyzeByMmseg4j() {

        try {
            Analyzer analyzer = new MMAnalyzer();
            Directory directory = new RAMDirectory();
            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
            IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);

            for (String fragment : chineseFragments) {

                Document document = new Document();
                document.add(new TextField("text", fragment, Field.Store.YES));
                indexWriter.addDocument(document);
            }

            indexWriter.close();

            IndexReader reader = DirectoryReader.open(directory);
            IndexSearcher searcher = new IndexSearcher(reader);
            QueryParser queryParser = new QueryParser(Version.LUCENE_CURRENT, "text", analyzer);
            Query query = queryParser.parse("\"中文\"");


            TopDocs topDocs = searcher.search(query, 10);
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                Document document = searcher.doc(scoreDoc.doc);
                System.out.println("查到了:" + document.get("text"));

            }
            reader.close();
            directory.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
    }
}